<template>
  <el-dialog
    class="eldialog"
    :visible.sync="visible"
    :title="title"
    :close-on-click-modal="false"
    width="40%"
    top="2vh"
    append-to-body
    @close="closeDialog"
    v-loading="loading"
    :close-on-press-escape="false"
  >
    <div style="height: 440px; overflow-y: auto; overflow-x: hidden">
      <el-tree
        :key="treeKye"
        ref="tree"
        :props="props"
        :load="loadNode"
        node-key="jg_id"
        :default-checked-keys="checkedId"
        lazy
        show-checkbox
      >
      </el-tree>
    </div>
    <template slot="footer">
      <el-button type="success" size="medium" @click="onSubmit">保存</el-button>
      <el-button type="danger" size="medium" @click="visible = false"
        >取消</el-button
      >
    </template>
  </el-dialog>
</template>
  <script>
import {
  getRoleTreeList,
  getRoleTreeSave,
  getTreeLeafLazy,
  getOrgTreeLazyHeader,
} from "@/api/datacentersg/achives/documentApi";
import store from "@/store";
export default {
  name: "ModuleTree",
  data() {
    return {
      title: "权限组维护",
      visible: false,
      roleId: "",
      valid: "",
      dataForm: {
        roleId: "",
        semiId: [],
      },
      props: {
        label: "jg_mingcheng",
        id: "jg_id",
        code: "jg_bianma",
        children: "children",
        parentId: "jg_shangji",
        type: "jg_leixing",
        icon: "icon",
        shortName: "jgjc",
        isLeaf: "leaf",
      },
      // 默认选中的
      checkedId: [],
      // 默认展开
      defaultCheckedId: [],
      loading: false,
      data: [],
      flag: "1",
      nodeId: "",
      getRoleDeptsData: [],
      node: "",
      treeKye: 0,
      node_had:'',
      resolve_had :''
    };
  },
  methods: {
    async initItemPermissions(params) {
      this.articlesData = null;
      const that = this;
      that.roleId = "";
      const dataChange = [];
      that.roleId = params.roleId;
      this.visible = true;
    },

    initGetRoleTreeList() {
      console.log(1111);
      return new Promise((resolve, reject) => {
        const paramsTreeList = {
          data: {
            roleId: this.roleId,
          },
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
        };
        getRoleTreeList(paramsTreeList).then((result) => {
          if (result.result) {
            this.getRoleDeptsData = result.resultdata.data;
            resolve(this.getRoleDeptsData);
          }
        });
      });
    },
    requestNewData() {
      this.node_had.childNodes = [];//把存起来的node的子节点清空，不然会界面会出现重复树！
      this.loadNode(this.node_had, this.resolve_had);//再次执行懒加载的方法
    },
    loadNode(node, resolve) {
      if (
        Array.isArray(this.getRoleDeptsData) &&
        this.getRoleDeptsData.length <= 0
      ) {
        this.initGetRoleTreeList().then((res) => {
          // 第一次加载需要等待 选择的数据接口请求完成以后才，调用全部数据
          // 再 判断是否有需要回显对勾的
          this.getAllTree(node).then((res) => {
            let list = res.map((e) => {
              let checked = false;
              this.getRoleDeptsData.forEach((item) => {
                this.checkedId.push(item.orgId);
              });
              return {
                ...e,
                checked,
              };
            });
            this.setChildNodeChecked(node, 100);
            resolve(list);
          });
        });
      } else {
        // 已经获取到 已经选择的数据了，直接加载更新的数据，判断是否有需要回显对勾的
        this.getAllTree(node).then((res) => {
          let list = res.map((e) => {
            let checked = false;

            this.getRoleDeptsData.forEach((item) => {
              this.checkedId.push(item.orgId);
            });
            return {
              ...e,
              checked,
            };
          });
          this.setChildNodeChecked(node, 100);
          resolve(list);
        });
      }
    },
    getAllTree(node) {
      console.log(222);
      return new Promise((resolve, reject) => {
        const userInfo = JSON.parse(sessionStorage.getItem(`userInfo`)) || {};
        if (node.level === 0) {
          this.node_had = node;//这里是关键！在data里面定义一个变量，将node.level == 0的node存起来
          this.resolve_had = resolve;//同上，把node.level == 0的resolve也存起来
          const paramsNew = {
            userId: store.getters.user_id.toString(),
            token: store.getters.token.toString(),
            system: "officedo",
            isEnableEditOrg: userInfo.isEnableEditOrg.toString(),
            is_show_org_inside: this.flag,
            data: {},
          };
          getOrgTreeLazyHeader(paramsNew).then((resultdata) => {
            if (resultdata.result) {
              console.log(resultdata.resultdata,"这是最顶层的数据")
              resolve(resultdata.resultdata);
            } else {
              resolve();
            }
          });
        }

        if (node.level > 0) {
          const userInfo = JSON.parse(sessionStorage.getItem(`userInfo`)) || {};
          const params = {
            userId: store.getters.user_id.toString(),
            token: store.getters.token.toString(),
            system: "officedo",
            isEnableEditOrg: userInfo.isEnableEditOrg.toString(),
            is_show_org_inside: this.flag,
            data: {},
            jg_id: node.data.jg_id,
          };
          getTreeLeafLazy(params).then(function (result) {
            resolve(result.resultdata);
          });
        }
      });
    },
    refsh() {
      return new Promise((resolve, reject) => {
        const userInfo = JSON.parse(sessionStorage.getItem(`userInfo`)) || {};
        const paramsNew = {
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          system: "officedo",
          isEnableEditOrg: userInfo.isEnableEditOrg.toString(),
          is_show_org_inside: this.flag,
          data: {},
        };
        getOrgTreeLazyHeader(paramsNew).then((resultdata) => {
          if (resultdata.result) {
            resolve(resultdata.resultdata);
          } else {
            resolve();
          }
        });
        this.initGetRoleTreeList();
      });
    },
    setChildNodeChecked(node, time) {
      this.node = node;
      setTimeout(() => {
        let count = 0;
        node.childNodes &&
          node.childNodes.forEach((cell) => {
            if (!this.checkedId.find((val) => val == cell.data.jg_id)) {
              count += 1;
              cell.checked = false;
            } else {
              cell.checked = cell.checked;
            }
          });
        if (count != 0 && node.childNodes.length != count) {
          node.checked = false;
          node.indeterminate = true;
        }
      }, time);
    },

    // 表单提交
    async onSubmit() {
      this.loading = true;
      const res = this.$refs.tree.getCheckedNodes(); // getCheckedNodes(false, true) 第一个参数 是否只获取叶子结点，第二个参数：当父节点下不全选的时候，也获取父节点的id
      const params = {
        data: {
          roleId: this.roleId,
          orgIds: "",
          codes: "",
          numbers: "",
        },
        userId: store.getters.user_id.toString(),
        token: store.getters.token.toString(),
      };
      this.getRoleDeptsData = [];
      if (this.getRoleDeptsData.length > 1) {
        this.getRoleDeptsData.forEach((item) => {
          params.data.orgIds += item.orgId + ",";
          params.data.numbers += item.orgNumber + ",";
          params.data.codes += item.orgCode + ",";
        });
      } else {
        res.forEach((items) => {
          params.data.orgIds += items.jg_id + ",";
          params.data.numbers += items.jgNumber + ",";
          params.data.codes += items.jgShangjiPlus + ",";
        });
      }

      getRoleTreeSave(params).then((result) => {
        if (result.result) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
          this.$emit("initData");
          this.closeDialog();
          this.visible = false;
          this.loading = false;
        }
      });
    },
    //关闭弹框的事件
    closeDialog() {
      this.visible = false;
      this.requestNewData();
      this.$emit("onAddSuccess", this.visible);
    },
  },
};
</script>
  
  <style scoped>
</style>
  